import React from 'react'
import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button ,Radio,Modal,Message,Upload,InputNumber} from 'antd';
import api from '../../../api/adSaleManage';
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const { TextArea } = Input;


import AreaCascader from '../../Cascader/AreaCascader';
import PanelBox from '../../../components/PanelBox';
import {INTERFACE_CORE_URL} from '../../../api/config';


import './index.less'

function beforeUpload(file) {
  /*const isJPG = file.type === 'image/jpeg';
  if (!isJPG) {
    Message.error('您只能上传图片格式的文件!');
  }*/
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    Message.error('上传的图片必须小于等于2MB!');
  }
  return isLt2M;
}
class EditForm extends React.Component {
  state = {
    sumitLoad: false,
    children:[],
  };
  componentWillReceiveProps(nextProps) {
    if (this.props.clearForm != nextProps.clearForm && nextProps.clearForm == false) {
      this.setState({
        imageUrl: '',
      })
      this.props.form.resetFields();
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const result=values.photos.file;
        if(typeof(result) != "undefined"){
          const data=result.response.data;
          values.photos='["'+data.fullPath+'"]';
        }
        if(values.hardIds.length>0){
           let hard='';
           values.hardIds.forEach(function(value, index, array) {
             hard=value+","+hard
           })
           hard=hard.substring(0,hard.length-1);
          values.hardIds=hard;
        }
        if(values.areaId && values.areaId.length>0){
         values.areaId=values.areaId[values.areaId.length-1];
       }
     
        this.setState({
          sumitLoad: true
        });
        if(values.id){
          this.update(values);
        }else{
          this.add(values);
        }
       
      }
    });
  }
  update= (values) =>{
    api.put('/adSaleManage/update', {...values}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('修改成功！');
      const { close,refeshData } = this.props;
      refeshData();
      close();
     }else{
      Message.error(result.message);
     }
     this.setState({
       sumitLoad: false
     });
    });
  }
  add= (values) =>{
    delete values['id'];
    api.post('/adSaleManage/add', {...values}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('添加成功！');
      const { close,refeshData } = this.props;
      refeshData();
      close();
     }else{
      Message.error(result.message);
     }
     this.setState({
        sumitLoad: false
      });
    });
  }
  handleImageChange = (info) => {
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      if(info.file.response){
        this.setState({ imageUrl:info.file.response.data.fullPath + '?process=image/resize,width_150,height_150'})
      }
    }
  }
  clearPho = () => {
    this.setState({
      imageUrl:undefined
    });
  }
  
   componentDidMount = () =>{
      
     
    }

 
 styleTailFormItemLayout={
  wrapperCol: {
    xs: {
      span: 14,
      offset: 0,
    },
    sm: {
      span: 14,
      offset: 6,
    },
  },
};
styleFormItemLayout= {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

optionHardList=(hardList)=>{
  let children=[];
  hardList.forEach(function(value, index, array) {
    children.push(<Option key={value.id} >{value.name}({value.address})</Option>);
  }) 
  return children;
}

validPriceExact=(rule, value, callback)=>{
if(value<5){
  callback('精准广告套餐单价不能少于5元（1天/1硬件）');
}else{
  callback();
}
}
validPriceCarousel=(rule, value, callback)=>{
  if(value<3){
    callback('轮播广告套餐单价不能少于3元（1天/1硬件）');
  }else{
    callback();
  }
  }

  render() {
    const _this = this;
    const { getFieldDecorator,resetFields } = this.props.form;
    const { close,refeshData,callbackParent} = this.props;
    callbackParent({
      resetFields:resetFields,
    });

    const record = this.props.rowRecord;
    const hardList =this.props.hardList;
    let optionHeardChildren=[];
    if(typeof(hardList) != 'undefined' && hardList.length>0){
      optionHeardChildren = this.optionHardList(hardList);
    }

    const formItemLayout =this.styleFormItemLayout;
    const tailFormItemLayout =this.styleTailFormItemLayout;

    const imageUrl = this.state.imageUrl;
   let imgStyle={};
    if(record.photos){
      let phos=JSON.parse(record.photos);
      let photo=phos[0];
      record.widthImg=photo+"?process=image/resize,width_150,height_150";
      let url="";
      if(imageUrl){
        url=imageUrl;
      }else{
        url=record.widthImg;
      }
      imgStyle={background:"url("+url+") center center no-repeat"};
    }else{
      imgStyle={background:"url("+imageUrl+") center center no-repeat"};
    }
 
    let hardInitialValue=[];
    if(record.hardIds){
       hardInitialValue= record.hardIds.split(",");
    }
    return (
      <div>
      <Form onSubmit={this.handleSubmit}>
          {getFieldDecorator('id', {
            initialValue:record ? record.id : ''
          })(
            <Input  type="hidden" />
          )}
      <FormItem
          {...formItemLayout}
          label="套餐图片"
          hasFeedback
        >
          {getFieldDecorator('photos', {
            rules: [{
              required: true, message: '请上传一个图片!',
            }],
            initialValue:record?record.photos:''
          })(
            <Upload
              className="avatar-uploader"
              name="file"
              showUploadList={false}
              action={INTERFACE_CORE_URL+"/upload"}
              beforeUpload={beforeUpload}
              onChange={_this.handleImageChange}
              accept="image/*"
            >
              {
                record ? 
                (imageUrl || record.photos) ?
                <div style={imgStyle} className="avatar" ></div> :
                <Icon type="plus" className="avatar-uploader-trigger" />
                : 
                (imageUrl) ?
                <div style={imgStyle} className="avatar" ></div> :
                <Icon type="plus" className="avatar-uploader-trigger" />
              }
            </Upload>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="套餐名称"
        >
            {getFieldDecorator('name', {
                rules: [{ required: true, message: '套餐名称不能为空!' }],
                initialValue:record ? record.name : ''
              })(
              <Input  placeholder="请输入套餐名称" />
           )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="天数"
          hasFeedback
        >
          {getFieldDecorator('days', {
            rules: [{ required: true, message: '天数不能为空!' }],
            initialValue:record ? record.days : ''
          })(
            <Input placeholder="请输入套餐天数"/>
          )}
        </FormItem>
        
        <FormItem
          {...formItemLayout}
          label="关联硬件"
        >
          {getFieldDecorator('hardIds', {
            rules: [{ required: true, message: '请关联硬件' }],
            initialValue:hardInitialValue
          })(
            <Select
            mode="multiple"
            placeholder="关联硬件"
          >
           {optionHeardChildren}
          </Select>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="精准广告单价"
          hasFeedback
        >
        <Tooltip placement="topLeft" title="精准广告单价(1天/1硬件),不能低于5元(1天/1硬件)">
          {getFieldDecorator('accuratePrice', {
            rules: [{ required: true, message: '价格不能为空!' },
            { validator: this.validPriceExact}],
            initialValue:record ? record.accuratePrice : 5
          })(
            <InputNumber />
          )}
          </Tooltip>
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="轮播广告单价"
          hasFeedback
        >
        <Tooltip placement="topLeft" title="轮播广告单价(1天/1硬件),不能低于3元(1天/1硬件)">
          {getFieldDecorator('turnPrice', {
            rules: [{ required: true, message: '价格不能为空!' },
            { validator: this.validPriceCarousel}],
            initialValue:record ? record.turnPrice : 3
          })(
            <InputNumber />
          )}
          </Tooltip>
        </FormItem>

        <FormItem
          {...formItemLayout}
          label="联系人"
        >
          {getFieldDecorator('contacts', {
            rules: [{ required: true, message: '联系人不能为空!' }],
            initialValue:record ? record.contacts : ''
          })(
            <Input placeholder ="请输入联系人"/>
          )}
        </FormItem> 
        <FormItem
          {...formItemLayout}
          label="联系电话"
        >
          {getFieldDecorator('phone', {
            rules: [{ required: true, message: '联系电话不能为空!' }],
            initialValue:record ? record.phone : ''
          })(
            <Input placeholder ="请输入联系电话"/>
          )}
        </FormItem> 
        <FormItem
            {...formItemLayout}
            label="所属区域"
            hasFeedback
          >
            {getFieldDecorator('areaId', {
              rules: [{type:"array", required: true, message: '不能为空' }],
              initialValue: record ? record.areaId : ''
            })(
              <AreaCascader/>
              )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="是否开放购买"
        >
          {getFieldDecorator('allowBuy', {
            rules: [{ required: true, message: '是否开放购买？' }],
            initialValue:record?record.allowBuy:1
          })(
            <RadioGroup name="allowBuy">
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </RadioGroup>
          )}
        </FormItem>
        
        <FormItem {...tailFormItemLayout}>
          <Button type="primary" htmlType="submit" size="large" style={{marginRight:'10px'}}>提交</Button>
          <Button onClick={close}>取消</Button>
          
        </FormItem>
      </Form>
       </div>
    );
  }
}

const WrappedEditForm = Form.create()(EditForm);
export default WrappedEditForm
